<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post请求</title>
</head>
<body>
    <h1>post请求</h1>
    <form action="" method="" id="form">
        <input type="text" id="ipt1">
        <input type="text" id="ipt2">
        <input type="text" id="ipt3">
        <button id="btn">提交</button>
    </form>

    <script>
        const form = document.getElementById('form')
        const iptName = document.getElementById('ipt1')
        const iptAge = document.getElementById('ipt2')
        const iptSex = document.getElementById('ipt3')

        form.onsubmit = function(){
            const name = iptName.value
            const age = iptAge.value
            const sex = iptSex.value

            const xhr = new XMLHttpRequest();
            xhr.open("post","/adduser",true)

            //因为请求体类型有很多,所以发送请求的时候一定要设置请求头的Content-Type类型
            //1.发送提交表单类型:
            // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charest=utf-8")
            // xhr.send(`name=${name}&age=${age}&sex=${sex}`)

            //2.发送json字符串类型:
            // xhr.setRequestHeader("Content-Type","application/json;charset=utf-8")
            // xhr.send(JSON.stringify({
            //     name: name,
            //     age: age,
            //     sex: sex
            // }))


            // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
            // xhr.send(`name=${name}&age=${age}&sex=${sex}`)

            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            xhr.send(JSON.stringify({
                name: name,
                age: age,
                sex: sex,
            }))


            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)){
                    const data = JSON.parse(xhr.responseText)
                    console.log(data);
                }
            }

            return false
        }
    </script>
</body>
</html>